#include "threadpool.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>


struct thread_pool *create_threadpool(int threads,int max_que_len,void *(*fun)(void *)){
    struct thread_pool *pool = malloc(sizeof(struct thread_pool));
    memset(pool,0,sizeof(struct thread_pool));

    pool->tids = malloc(sizeof(pthread_t)*threads);
    memset(pool->tids,0,sizeof(pool->tids));

    pool->que = create_tqueue();
    pool->threads = threads;
    sem_init(&pool->semw,0,max_que_len);
    sem_init(&pool->semr,0,0);
    pthread_mutex_init(&pool->mutex,NULL);
    int ret = 0;

     for(int i = 0;i < threads;i++){
        ret = pthread_create(&pool->tids[i],NULL,fun,pool);
        if(ret != 0){
            printf("pthread_create error");
            exit(-1);
        }
    }

    return pool;
}


void destroy_threadpool(struct thread_pool *pool){
    sem_destroy(&pool->semr);
    sem_destroy(&pool->semw);
    pthread_mutex_destroy(&pool->mutex);
    // freeque(pool->que);
    free(pool->tids);
    free(pool);
}
